package com.lzh.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.lzh.ThreadLocalUtils;
import com.lzh.bean.CustomerInquiry;
import com.lzh.bean.CustomerInquiryDetail;
import com.lzh.common.utils.Assert;
import com.lzh.common.utils.DateUtil;
import com.lzh.mapper.InquiryDetailMapper;
import com.lzh.mapper.InquiryMapper;
import com.lzh.service.InquiryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class InquiryServiceImpl implements InquiryService {


    @Autowired
    private InquiryMapper inquiryMapper;

    @Autowired
    InquiryDetailMapper inquiryDetailMapper;

    //默认最大编码
    String maxCode;

    //默认询价单前缀
    String INQUIRY_CODE_BEFORE="XJ";
    /**
     * 保存询价单
     * @param customerInquiry
     * @return
     */
    @Override
    public int saveInquiry(CustomerInquiry customerInquiry) {
        int i = 0;
        //生成编码
        customerInquiry.setCode(getNewCode());
        //设置登陆人
        //把线程里的内容拿出来
        Map map = ThreadLocalUtils.getInstance().get();
        //获取里面操作人的id
        customerInquiry.setCid(Integer.parseInt(map.get("id").toString()));
        ThreadLocalUtils.getInstance().remove();
        //保存询价单
        int save = inquiryMapper.save(customerInquiry);
        Assert.isZerp(save,"保存询价单失败");
        //保存询价明细
        if (null!=customerInquiry.getCustomerInquiryDetails()&&customerInquiry.getCustomerInquiryDetails().size()>0){
            //批量保存
            i = inquiryDetailMapper.saveInquiryDetail(customerInquiry.getId(), customerInquiry.getCustomerInquiryDetails());
            Assert.isZerp(i,"保存询价单明细失败");
        }
        int result = save+i;
        return result;
    }


     String  getNewCode(){
        String ym = DateUtil.getSystemTimeYm();
        //内存中不存在最大编码
        if (maxCode==null){
            //查询最大编码
            maxCode = inquiryMapper.queryMaxCode();
            if (maxCode==null){
                //如果最大编码是空的话
                //设置一个自定义的编码
                //询价单前缀+当前年月+0001
                maxCode=INQUIRY_CODE_BEFORE+ ym + "0001";
                return maxCode;
            }
        }

        //内存中存在最大编码
        //判断是否是当月的
        //XJYYMM0001
        if (maxCode.substring(2,6).equals(ym)){
            //是当月的，后面的数+1
            int code = Integer.parseInt(maxCode.substring(6));
            code = code + 1;
            String result = String.format("%04d", code);
            maxCode = maxCode.substring(0, 6) + result;
            return maxCode;
        }

        //不是当月的，判断是否为最大编码
        maxCode=INQUIRY_CODE_BEFORE+ ym + "0001";
        return maxCode;
    }

}
